package model

import (
	"common/helper"
	"database/sql"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"strconv"
)

func GameConfigByType(cfg_type int) TblGameConfig {
	data := TblGameConfig{}

	query, _, _ := dialect.From("tbl_game_config").Select(colsGameConfig...).Where(g.Ex{"cfg_type": cfg_type}).ToSQL()

	_ = meta.MerchantDB.Get(&data, query)
	return data
}

func GetProxyLevelGameConfig(types []int32) []TblGameConfig {
	var data []TblGameConfig
	values := g.Ex{"cfg_type": g.Op{"in": types}}
	query, _, _ := dialect.From("tbl_game_config").Select(colsGameConfig...).Where(values).ToSQL()
	_ = meta.MerchantDB.Select(&data, query)
	return data
}

func GameConfigUpdate(id string, data TblGameConfig) error {

	record := g.Record{
		"cfg_type":  data.CfgType,
		"cfg_value": data.CfgValue,
		//"description": data.Description,
		//"type_id":     data.TypeId,
	}
	query, _, _ := dialect.Update("tbl_game_config").Set(&record).Where(g.Ex{"id": id}).ToSQL()

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

func GameConfigUpdateValueByType(cfgType int, cfgValue string) error {
	record := g.Record{
		"cfg_value": cfgValue,
	}
	query, _, _ := dialect.Update("tbl_game_config").Set(&record).Where(g.Ex{"cfg_type": cfgType}).ToSQL()
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return nil
}

func GameConfigList(page, pageSize uint, ex g.Ex) (GameConfigData, error) {

	data := GameConfigData{}
	t := dialect.From("tbl_game_config")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()

		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsGameConfig...).Where(ex).Offset(offset).Limit(pageSize).Order(g.C("id").Asc()).ToSQL()

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	data.S = pageSize
	return data, nil
}

func GameConfigLoad() {
	var data []TblGameConfig
	query, _, _ := dialect.From("tbl_game_config").Select(colsGameConfig...).ToSQL()

	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {
		return
	}

	pipe := meta.MerchantRedis.Pipeline()
	defer pipe.Close()

	pipe.Del(ctx, "game_config")
	for _, v := range data {
		pipe.HSet(ctx, "game_config", v.CfgType, v.CfgValue)
		pipe.Persist(ctx, "game_config")

	}
	_, err = pipe.Exec(ctx)
	if err != nil {

	}
}

func GetWeekConfig() (WeekConfigRetData, error) {
	data := WeekConfigRetData{}

	query := "select * from tbl_cfg_week_deposit_return_rate order by id asc"
	err := meta.MerchantDB.Select(&data.Deposit, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	query = "select * from tbl_cfg_week_lost_return_rate order by id asc"
	err = meta.MerchantDB.Select(&data.Lost, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	query = "select * from tbl_cfg_week_proxy_commi_return_rate order by id asc"
	err = meta.MerchantDB.Select(&data.Commi, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	query = "select * from tbl_cfg_week_running_return_rate order by id asc"
	err = meta.MerchantDB.Select(&data.Running, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateGetWeekConfig(param UpdateWeekConfigParam, isDelete int8) error {
	table := ""
	query := ""
	record := g.Record{
		"return_rate": param.ReturnRate,
	}
	switch param.Ctype {
	case "deposit":
		table = "tbl_cfg_week_deposit_return_rate"
		record["deposit"] = param.Deposit
	case "lost":
		table = "tbl_cfg_week_lost_return_rate"
		record["running"] = param.Running
	case "commi":
		table = "tbl_cfg_week_proxy_commi_return_rate"
		record["deposit"] = param.Deposit
	case "running":
		table = "tbl_cfg_week_running_return_rate"
		record["running"] = param.Running
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetDailyConfig() (DailyConfigRetData, error) {
	data := DailyConfigRetData{}

	//query := "select * from tbl_cfg_daily_deposit_return_rate order by id asc"
	//err := meta.MerchantDB.Select(&data.Deposit, query)
	//if err != nil && err != sql.ErrNoRows {
	//
	//	return data, err
	//}
	//query = "select * from tbl_cfg_daily_lost_return_rate order by id asc"
	//err = meta.MerchantDB.Select(&data.Lost, query)
	//if err != nil && err != sql.ErrNoRows {
	//
	//	return data, err
	//}
	//query = "select * from tbl_cfg_daily_proxy_commi_return_rate order by id asc"
	//err = meta.MerchantDB.Select(&data.Commi, query)
	//if err != nil && err != sql.ErrNoRows {
	//
	//	return data, err
	//}
	query := "select * from tbl_cfg_daily_running_return_rate order by id asc"
	err := meta.MerchantDB.Select(&data.Running, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateDailyConfig(param UpdateDailyConfigParam, isDelete int8) error {
	table := ""
	query := ""
	record := g.Record{
		"return_rate": param.ReturnRate,
	}
	switch param.Ctype {
	case "deposit":
		table = "tbl_cfg_daily_deposit_return_rate"
		record["deposit"] = param.Deposit
	case "lost":
		table = "tbl_cfg_daily_lost_return_rate"
		record["running"] = param.Running
	case "commi":
		table = "tbl_cfg_daily_proxy_commi_return_rate"
		record["deposit"] = param.Deposit
	case "running":
		table = "tbl_cfg_daily_running_return_rate"
		record["running"] = param.Running
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetDepositConfig() ([]DepositAward, error) {
	data := []DepositAward{}

	query := "select * from tbl_cfg_accu_deposit_bonus order by id asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateDepositConfig(param DepositAward, isDelete int8) error {
	table := "tbl_cfg_accu_deposit_bonus"
	query := ""
	record := g.Record{
		"level":               param.Level,
		"accu_deposit_amount": param.AccuDepositAmount,
		"bonus":               param.Bonus,
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetDepositDivide() ([]DepositDivide, error) {
	data := []DepositDivide{}

	query := "select * from tbl_cfg_recharge_share_rate order by id asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateDepositDivide(param DepositDivide, isDelete int8) error {
	table := "tbl_cfg_recharge_share_rate"
	query := ""
	record := g.Record{
		"level": param.Level,
		"rate":  param.Rate,
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetInviteConfig() ([]ProxyInviteBonus, error) {
	data := []ProxyInviteBonus{}

	query := "select * from tbl_cfg_proxy_invite_bonus order by id asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateInviteConfig(param ProxyInviteBonus, isDelete int8) error {
	table := "tbl_cfg_proxy_invite_bonus"
	query := ""
	record := g.Record{
		"valid_Counts": param.ValidCounts,
		"bonus":        param.Bonus,
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetDepositInviteConfig() ([]ProxyDepositInviteBonus, error) {
	data := []ProxyDepositInviteBonus{}

	query := "select * from tbl_cfg_proxy_invite_bonus_by_deposit order by id asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateDepositInviteConfig(param ProxyDepositInviteBonus, isDelete int8) error {
	table := "tbl_cfg_proxy_invite_bonus_by_deposit"
	query := ""
	record := g.Record{
		"deposit": param.Deposit,
		"bonus":   param.Bonus,
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetUnbindConfig(param UnbindConfig, ctx *fasthttp.RequestCtx) ([]UnbindConfig, error) {
	where := "1=1"
	loginUser := GetLoginUser(ctx)
	if loginUser.Businsess != "" {
		where += " and 1=2"
	}
	if param.OperatorId != "" {
		where += " and operator_id=" + param.OperatorId
	}
	if loginUser.Operator != "" {
		where += " and operator_id=" + loginUser.Operator
	}
	data := []UnbindConfig{}

	query := "select * from tbl_cfg_disablebind where " + where + " order by InviteCounts asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateUnbindConfig(param UnbindConfig, ctx *fasthttp.RequestCtx, isDelete int8) error {

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		param.OperatorId = loginUser.Operator

	}
	if loginUser.Operator != "" || loginUser.Businsess != "" {
		s := GameConfigByType(276)
		if s.CfgValue == "1" {
			return errors.New("总台设置禁止掉绑")
		}
	}
	table := "tbl_cfg_disablebind"
	query := ""
	record := g.Record{
		"InviteCounts":    param.InviteCounts,
		"DisableBindRate": param.DisableBindRate,
		"max_disableBind": param.MaxDisableBind,
		"operator_id":     param.OperatorId,
	}
	if param.ID > 0 {
		data := UnbindConfig{}
		t := dialect.From(table)
		query, _, _ = t.Select("*").Where(g.Ex{"id": param.ID}).Limit(1).ToSQL()
		_ = meta.MerchantDB.Get(&data, query)
		if loginUser.Operator != "" {
			if data.OperatorId != loginUser.Operator {
				return errors.New("权限不足")
			}
		}
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else if param.ID == -1 {
		if isDelete == 1 {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"param.OperatorId": param.OperatorId}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetFlowConfig() ([]FlowConfig, error) {
	data := []FlowConfig{}

	query := "select * from tbl_flow_config order by id asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateFlowConfig(param FlowConfig, isDelete int8) error {
	table := "tbl_flow_config"
	query := ""
	record := g.Record{
		"name":          param.Name,
		"flow_multiple": param.FlowMultiple,
	}
	if param.Id > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"ty": param.Ty}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"ty": param.Ty}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func SynRedis(ctx *fasthttp.RequestCtx) {
	value := meta.MerchantRedis.Get(ctx, "cfg_version").Val()
	intValue, _ := strconv.Atoi(value)
	newValue := intValue + 1
	stringValue := strconv.Itoa(newValue)
	meta.MerchantRedis.Set(ctx, "cfg_version", stringValue, -1)
}

func GetFakePgList(param FakePgConfigParam) (FakePgConfigRetData, error) {
	data := FakePgConfigRetData{}

	where := "1=1"
	table := "tbl_cfg_fakepg"
	join := ""
	oderBy := "id"
	oderType := "desc"
	if param.PlatformId != 0 {
		where += " and a.platform_id=" + strconv.Itoa(param.PlatformId)
	} else {
		where += " and a.platform_id=100"
	}
	if param.PgId != "" {
		where += " and a.pg_id='" + param.PgId + "'"
	}

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateFakePgConfig(param FakePgConfig, isDelete int8) error {
	table := "tbl_cfg_fakepg"
	query := ""
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(param).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {

			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else if param.ID < 0 {
		query, _, _ = dialect.Update(table).Set(g.Ex{"status": param.Status}).Where(g.Ex{"platform_id": param.PlatformId}).ToSQL()
	} else {
		query, _, _ = dialect.Insert(table).Rows(param).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetFakePgRouteList(param FakePgConfigParam) (FakePgConfigRouteRetData, error) {
	data := FakePgConfigRouteRetData{}

	where := "1=1"
	table := "tbl_cfg_fakepg_route_info"
	join := ""
	oderBy := "id"
	oderType := "desc"

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateFakePgConfigRoute(param FakePgRouteConfig, isDelete int8) error {
	table := "tbl_cfg_fakepg_route_info"
	query := ""
	if param.ID > 0 {
		if isDelete == 0 {
			//if param.Test == 1 {
			//	query, _, _ = dialect.Update(table).Set(g.Record{
			//		"test": 0,
			//	}).ToSQL()
			//	//fmt.Println(query)
			//	_, _ = meta.MerchantDB.Exec(query)
			//}
			query, _, _ = dialect.Update(table).Set(param).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {

			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else if param.ID < 0 {
		query, _, _ = dialect.Update(table).Set(g.Ex{"status": param.Status}).ToSQL()
	} else {
		query, _, _ = dialect.Insert(table).Rows(param).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetFakePpRouteList(param FakePpConfigParam) (FakePpConfigRouteRetData, error) {
	data := FakePpConfigRouteRetData{}

	where := "1=1"
	table := "tbl_cfg_fakepp_route_info"
	join := ""
	oderBy := "id"
	oderType := "desc"

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateFakePpConfigRoute(param FakePpRouteConfig, isDelete int8) error {
	table := "tbl_cfg_fakepp_route_info"
	query := ""
	if param.ID > 0 {
		if isDelete == 0 {
			//if param.Test == 1 {
			//	query, _, _ = dialect.Update(table).Set(g.Record{
			//		"test": 0,
			//	}).ToSQL()
			//	//fmt.Println(query)
			//	_, _ = meta.MerchantDB.Exec(query)
			//}
			query, _, _ = dialect.Update(table).Set(param).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {

			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else if param.ID < 0 {
		query, _, _ = dialect.Update(table).Set(g.Ex{"status": param.Status}).ToSQL()
	} else {
		query, _, _ = dialect.Insert(table).Rows(param).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetFakePgCtrlList(param FakePgCtrlConfigParam) (FakePgCtrlResData, error) {
	data := FakePgCtrlResData{}

	where := "1=1"
	table := "tbl_cfg_entryfakepg"
	join := ""
	oderBy := "id"
	oderType := "desc"

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateFakePgCtrlConfig(param FakePgCtrlConfig, isDelete int8) error {
	table := "tbl_cfg_entryfakepg"
	query := ""
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(param).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else if param.ID < 0 {
		//query, _, _ = dialect.Update(table).Set(g.Ex{"status": param.Status}).ToSQL()
	} else {
		query, _, _ = dialect.Insert(table).Rows(param).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetThirdTax() (ThirdTaxRetData, error) {
	data := ThirdTaxRetData{}
	where := "1=1"
	table := "tbl_cfg_thirdgame"
	join := ""
	oderBy := "platformId"
	oderType := "asc"

	order := oderBy + " " + oderType

	if true {
		count := "select count(1) from " + table + " as a where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	join += " left join tbl_platforms as c on c.id=a.platformId" //游戏表
	field := "a.*,c.name as platform_name"

	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateThirdTax(param ThirdTax, isDelete int8) error {
	table := "tbl_cfg_thirdgame"
	query := ""
	if param.PlatformId > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(param).Where(g.Ex{"platformId": param.PlatformId}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"platformId": param.PlatformId}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(param).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetTaxConfig() ([]TaxConfig, error) {
	data := []TaxConfig{}

	query := "select * from tbl_cfg_tax order by ID asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateTaxConfig(param TaxConfig, isDelete int8) error {
	table := "tbl_cfg_tax"
	query := ""
	record := g.Record{
		"profit_amount": param.ProfitAmount,
		"tax_rate":      param.TaxRate,
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetAddwageConfig() ([]AddwageConfig, error) {
	data := []AddwageConfig{}

	query := "select * from tbl_cfg_add_wage order by ID asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateAddwageConfig(param AddwageConfig, isDelete int8) error {
	table := "tbl_cfg_add_wage"
	query := ""
	record := g.Record{
		"win_amount": param.WinAmount,
		"wage":       param.Wage,
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetValidwageConfig() ([]ValidwageConfig, error) {
	data := []ValidwageConfig{}

	query := "select * from tbl_cfg_valid_waged_rate order by ID asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateValidwageConfig(param ValidwageConfig, isDelete int8) error {
	table := "tbl_cfg_valid_waged_rate"
	query := ""
	record := g.Record{
		"bet_amount":       param.BetAmount,
		"valid_waged_rate": param.ValidWagedRate,
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetActiveSwitchConfig() ([]ActiveSwitch, error) {
	data := []ActiveSwitch{}

	query := "select * from tbl_cfg_active_switch order by ID asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateActiveSwitchConfigConfig(param ActiveSwitch, isDelete int8) error {
	table := "tbl_cfg_active_switch"
	query := ""
	record := g.Record{
		"status":       param.Status,
		"popup_switch": param.PopupSwitch,
	}
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetFakepgConfig(param FakepgConfig, ctx *fasthttp.RequestCtx) ([]FakepgConfig, error) {
	where := "1=1"
	loginUser := GetLoginUser(ctx)
	if loginUser.Businsess != "" {
		where += " and 1=2"
	}
	if param.OperatorId != "" {
		where += " and operator_id=" + param.OperatorId
	}
	if loginUser.Operator != "" {
		where += " and operator_id=" + loginUser.Operator
	}
	data := []FakepgConfig{}

	query := "select * from tbl_cfg_fakepg_rtp where " + where + " order by id asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateFakepgConfig(param FakepgConfig, ctx *fasthttp.RequestCtx, isDelete int8) error {

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		param.OperatorId = loginUser.Operator
	}

	table := "tbl_cfg_fakepg_rtp"
	query := ""
	record := g.Record{
		"money":       param.Money,
		"RTP":         param.RTP,
		"operator_id": param.OperatorId,
	}
	if param.ID > 0 {
		data := FakepgConfig{}
		t := dialect.From(table)
		query, _, _ = t.Select("*").Where(g.Ex{"id": param.ID}).Limit(1).ToSQL()

		_ = meta.MerchantDB.Get(&data, query)
		if loginUser.Operator != "" {
			if data.OperatorId != loginUser.Operator {
				return errors.New("权限不足")
			}
		}

		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetFakeppConfig(param FakeppConfig, ctx *fasthttp.RequestCtx) ([]FakeppConfig, error) {
	where := "1=1"
	loginUser := GetLoginUser(ctx)
	if loginUser.Businsess != "" {
		where += " and 1=2"
	}
	if param.OperatorId != "" {
		where += " and operator_id=" + param.OperatorId
	}
	if loginUser.Operator != "" {
		where += " and operator_id=" + loginUser.Operator
	}
	data := []FakeppConfig{}

	query := "select * from tbl_cfg_fakepp_rtp where " + where + " order by id asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateFakeppConfig(param FakeppConfig, ctx *fasthttp.RequestCtx, isDelete int8) error {

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		param.OperatorId = loginUser.Operator
	}

	table := "tbl_cfg_fakepp_rtp"
	query := ""
	record := g.Record{
		"money":       param.Money,
		"RTP":         param.RTP,
		"operator_id": param.OperatorId,
	}
	if param.ID > 0 {
		data := FakeppConfig{}
		t := dialect.From(table)
		query, _, _ = t.Select("*").Where(g.Ex{"id": param.ID}).Limit(1).ToSQL()

		_ = meta.MerchantDB.Get(&data, query)
		if loginUser.Operator != "" {
			if data.OperatorId != loginUser.Operator {
				return errors.New("权限不足")
			}
		}

		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetFakePpList(param FakePpConfigParam) (FakePpConfigRetData, error) {
	data := FakePpConfigRetData{}

	where := "1=1"
	table := "tbl_cfg_fakepp"
	join := ""
	oderBy := "id"
	oderType := "desc"
	if param.PlatformId != 0 {
		where += " and a.platform_id=" + strconv.Itoa(param.PlatformId)
	} else {
		where += " and a.platform_id=200"
	}
	if param.PgId != "" {
		where += " and a.pp_id='" + param.PgId + "'"
	}

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateFakePpConfig(param FakePpConfig, isDelete int8) error {
	table := "tbl_cfg_fakepp"
	query := ""
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(param).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {

			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else if param.ID < 0 {
		query, _, _ = dialect.Update(table).Set(g.Ex{"status": param.Status}).Where(g.Ex{"platform_id": param.PlatformId}).ToSQL()
	} else {
		query, _, _ = dialect.Insert(table).Rows(param).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetBlackBankCardList(param BlackBankCardParam) (BlackBankCardRetData, error) {

	data := BlackBankCardRetData{}

	where := "1=1"
	table := "tbl_cfg_bankcard_blacklist"
	join := ""
	oderBy := "id"
	oderType := "desc"

	if param.PixId != "" {
		where += " and pix_id=" + param.PixId
	}
	if param.Flag != "" {
		where += " and flag=" + param.Flag
	}
	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "id,flag,pix_id"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateBlackBankCard(param BlackBankCard, isDelete int8) error {
	table := "tbl_cfg_bankcard_blacklist"
	query := ""
	if param.Id > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(param).Where(g.Ex{"id": param.Id}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.Id}).ToSQL()
		}
	} else {
		has := BlackBankCard{}
		meta.MerchantDB.Get(&has, fmt.Sprintf("select * from tbl_cfg_bankcard_blacklist where flag='%s' and pix_id='%s'", param.Flag, param.PixId))
		if has.Id > 0 {
			return errors.New(helper.BankCardExistErr)
		} else {
			query, _, _ = dialect.Insert(table).Rows(param).ToSQL()
		}
	}
	fmt.Println(query)
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetBlackEmailList(param BlackEmailParam) (BlackEmailRetData, error) {

	data := BlackEmailRetData{}

	where := "1=1"
	table := "tbl_cfg_email_suffix_blacklist"
	join := ""
	oderBy := "id"
	oderType := "desc"

	if param.EmailSuffix != "" {
		where += " and email_suffix='" + param.EmailSuffix + "'"
	}
	if param.State != "" {
		where += " and state='" + param.State + "'"
	}
	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "id,email_suffix,state"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateBlackEmail(param BlackEmail, isDelete int8) error {
	table := "tbl_cfg_email_suffix_blacklist"
	query := ""
	if param.Id > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(param).Where(g.Ex{"id": param.Id}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.Id}).ToSQL()
		}
	} else {
		has := BlackEmail{}
		meta.MerchantDB.Get(&has, fmt.Sprintf("select * from tbl_cfg_email_suffix_blacklist where email_suffix='%s'", param.EmailSuffix))
		if has.Id > 0 {
			return errors.New(helper.EmailExist)
		} else {
			query, _, _ = dialect.Insert(table).Rows(param).ToSQL()
		}
	}
	fmt.Println(query)
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}
